using System;
using System.Collections.Generic;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Data;
using InfoExpress.WinApp.Utils;
using InfoExpress.HIV.Domains;
using InfoExpress.HIV.WinApp.Utils;
using InfoExpress.HIV.Services;

namespace InfoExpress.HIV.WinApp.Popups
{
  public partial class FrmChamDutDieuTri : XtraForm
  {
    private int _benhNhanId = 0;
    private string _maBenhNhan = string.Empty;
    private DieuTri _dieuTri;
    private DateTime? _ngayDangKy;
    private TList<UtDmdv> _donViList;

    public FrmChamDutDieuTri()
    {
      InitializeComponent();
    }

    public FrmChamDutDieuTri(int benhNhanId, string maBenhNhan)
      : this()
    {
      _benhNhanId = benhNhanId;
      _maBenhNhan = maBenhNhan;
    }

    #region Event Handlers

    private void FrmChamDutDieuTri_Load(object sender, EventArgs e)
    {
      if(Owner is FrmChonBenhNhan)
      {
        _benhNhanId = ((FrmChonBenhNhan)Owner).BenhNhanId;
        _maBenhNhan = ((FrmChonBenhNhan)Owner).MaBenhNhan;
        _ngayDangKy = (DateTime?)((FrmChonBenhNhan)Owner).NgayDangKy;
      }

      BindData();
      LoadData();
    }

    #region Command Handlers

    private void btnOK_Click(object sender, EventArgs e)
    {
      bool isValid = true;

      if (lueOPC.Enabled)
        isValid = dxValidationProvider.Validate();
      
      if (isValid & CheckInput())
      {
        if (UIUtils.ShowQuestionMessage(Constants.MsgQusChamDutDieuTri_001) == DialogResult.Yes)
        {
          try
          {
            if (rgLyDoChamDut.SelectedIndex == 2)
            {
              ChuyenOpcBuffer buffer = new ChuyenOpcBuffer
              {
                BenhNhanId = _benhNhanId,
                MaOpc = txtOPC1.Text,
                ToiOpc = (string)lueOPC.EditValue,
                Ngay = deNgayChamDut.DateTime
              };

              GlobalCache.ChuyenOpcBufferService.Save(buffer);

              _dieuTri.UserChamDut = GlobalCache.Permission.Username;
              GlobalCache.DieuTriService.Save(_dieuTri);
            }
            else
            {
              _dieuTri.MaChamDutDieuTri = (int)rgLyDoChamDut.EditValue;
              _dieuTri.NgayChamDutDieuTri = deNgayChamDut.DateTime;
              _dieuTri.UserChamDut = GlobalCache.Permission.Username;

              TList<LichSuDieuTri> lsDieuTriList = GlobalCache.LichSuDieuTriService.LayLichSuMoiNhat(_benhNhanId);
              if (lsDieuTriList.Count > 0)
              {
                LichSuDieuTri lsDieuTriMoi = new LichSuDieuTri { 
                  BenhNhanId = lsDieuTriList[0].BenhNhanId, 
                  MaOpc = lsDieuTriList[0].MaOpc, 
                  NgayBatDau = lsDieuTriList[0].NgayBatDau, 
                  NgayDangKyArv = lsDieuTriList[0].NgayDangKyArv, 
                  TuOpc = lsDieuTriList[0].TuOpc, 
                  OpcGoc = lsDieuTriList[0].OpcGoc, 
                  MaKetThuc = (int)rgLyDoChamDut.EditValue, 
                  NgayKetThuc = deNgayChamDut.DateTime };

                GlobalCache.LichSuDieuTriService.Save(lsDieuTriMoi);
              }

              GlobalCache.DieuTriService.Save(_dieuTri);
            }

            DialogResult = DialogResult.OK;
            Close();            

            //For Non-Webservice
            //using (ConnectionScope.CreateTransaction())
            //{
            //  if (rgLyDoChamDut.SelectedIndex == 2)
            //  {
            //    ChuyenOpcBuffer buffer = new ChuyenOpcBuffer { 
            //      BenhNhanId = _benhNhanId, 
            //      MaOpc = txtOPC1.Text, 
            //      ToiOpc = (string)lueOPC.EditValue, 
            //      Ngay = deNgayChamDut.DateTime };

            //    GlobalCache.ChuyenOpcBufferService.Save(buffer);

            //    _dieuTri.UserChamDut = GlobalCache.Permission.Username;
            //    GlobalCache.DieuTriService.Save(_dieuTri);
            //  }
            //  else
            //  {
            //    _dieuTri.MaChamDutDieuTri = (int)rgLyDoChamDut.EditValue;
            //    _dieuTri.NgayChamDutDieuTri = deNgayChamDut.DateTime;

            //    GlobalCache.DieuTriService.Save(_dieuTri);
            //  }

            //  if (ConnectionScope.Complete())
            //  {
            //    DialogResult = DialogResult.OK;
            //    Close();
            //  }
            //  else
            //  {
            //    UIUtils.ShowErrorMessage(Constants.MsgErrSave);
            //  }
            //}
          }
          catch (Exception ex)
          {
            Logger.LogCritical("FrmChamDutDieuTri::btnOK_Click", ex, "General", null);
            UIUtils.ShowCannotSaveDataMessage();
          }
        }
      }
    }

    private void btnReject_Click(object sender, EventArgs e)
    {
      try
      {
        using (ConnectionScope.CreateTransaction())
        {
          _dieuTri.UserChamDut = null;
          GlobalCache.ChuyenOpcBufferService.Delete(_benhNhanId);
          GlobalCache.DieuTriService.Save(_dieuTri);

          if (ConnectionScope.Complete())
          {
            DialogResult = DialogResult.OK;
            Close();
          }
          else
          {
            UIUtils.ShowErrorMessage(Constants.MsgErrSave);
          }
        }
      }
      catch (Exception ex)
      {
        Logger.LogCritical("FrmChamDutDieuTri::btnReject_Click", ex, "General", null);
        UIUtils.ShowCannotSaveDataMessage();
      }
    }

    #endregion

    #region GUI Processing Handlers

    private void rgLyDoChamDut_SelectedIndexChanged(object sender, EventArgs e)
    {
      lueOPC.Enabled = (rgLyDoChamDut.SelectedIndex == 2);
    }

    #endregion

    #endregion

    #region Helper Methods

    private void BindData()
    {
      _donViList = GlobalCache.DonViService.GetAll();
      UtDmdv donVi = _donViList.Find("FMadv", GlobalCache.Permission.UnitCode);
      _donViList.Remove(donVi);

      lueOPC.Properties.DataSource = _donViList;
    }

    private void LoadData()
    {
      try
      {
        txtMaThe.Text = _maBenhNhan;
        deNgayChamDut.DateTime = _ngayDangKy ?? DateTime.Today;

        DataSet dtsDieuTri = GlobalCache.DieuTriService.KiemTraTonTai(_maBenhNhan, null, false, true, null);
        DataTable dtbDieuTri = dtsDieuTri.Tables[0];
        if (dtbDieuTri.Rows.Count > 0)
        {
          DataRow dataRow = dtbDieuTri.Rows[0];
          txtOPC1.EditValue = dataRow["MaDonVi"];
          txtOPC2.EditValue = dataRow["TenDonVi"];

          TList<DieuTri> dieuTriList =
              GlobalCache.DieuTriService.LayDieuTriLanCuoi(_maBenhNhan, null, false, true, null);

          if (dieuTriList.Count > 0)
            _dieuTri = dieuTriList[0];

          ChuyenOpcBuffer chuyenOpcBuffer = GlobalCache.ChuyenOpcBufferService.GetByBenhNhanId(_benhNhanId);
          if (chuyenOpcBuffer != null)
          {
            deNgayChamDut.EditValue = chuyenOpcBuffer.Ngay;
            rgLyDoChamDut.SelectedIndex = 2; //Chuyen OPC
            lueOPC.EditValue = chuyenOpcBuffer.ToiOpc;

            deNgayChamDut.Enabled = false;
            rgLyDoChamDut.Enabled = false;
            lueOPC.Enabled = false;
            btnOK.Enabled = false;
          }
        }
      }
      catch (Exception ex)
      {
        Logger.LogCritical("FrmChamDutDieuTri::LoadData", ex, "General", null);
        UIUtils.ShowCannotLoadDataMessage();
      }
    }

    private bool CheckInput()
    {
      bool isValid = true;

      if (_dieuTri.NgayTiepNhanDieuTri > deNgayChamDut.DateTime)
      {
        isValid = false;
        UIUtils.ShowErrorMessage(Constants.MsgErrChamDutDieuTri_001);
      }

      return isValid;
    }

    #endregion
  }
}